package com.summerbird.mallchat.common.user.service.impl;

import com.summerbird.mallchat.common.common.annotation.RedissonLock;
import com.summerbird.mallchat.common.common.domain.vo.resp.ApiResult;
import com.summerbird.mallchat.common.common.domain.vo.resp.IdRespVO;
import com.summerbird.mallchat.common.common.utils.AssertUtil;
import com.summerbird.mallchat.common.user.dao.UserEmojiDao;
import com.summerbird.mallchat.common.user.domain.entity.UserEmoji;
import com.summerbird.mallchat.common.user.domain.vo.req.UserEmojiReq;
import com.summerbird.mallchat.common.user.domain.vo.resp.UserEmojiResp;
import com.summerbird.mallchat.common.user.service.UserEmojiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class UserEmojiServiceImpl implements UserEmojiService {

    @Autowired
    private UserEmojiDao userEmojiDao;

    @Override
    public List<UserEmojiResp> list(Long uid) {
        return userEmojiDao.listByUid(uid).stream()
                .map(a -> UserEmojiResp.builder()
                        .id(a.getId())
                        .expressionUrl(a.getExpressionUrl())
                        .build())
                .collect(Collectors.toList());
    }

    @Override
    @RedissonLock(key = "#uid")
    public ApiResult<IdRespVO> insert(UserEmojiReq req, Long uid) {
        // 检测表情包数量是否超过30
        int count = userEmojiDao.countByUid(uid);
        AssertUtil.isFalse(count > 30, "最多只能添加30个表情包哦~");
        // 检测表情包之前是否存在
        UserEmoji userEmoji = userEmojiDao.get(req.getExpressionUrl(), uid);
        AssertUtil.isEmpty(userEmoji, "该表情包已存在");
        UserEmoji insert = UserEmoji.builder().expressionUrl(req.getExpressionUrl()).uid(uid).build();
        userEmojiDao.save(insert);
        return ApiResult.success(IdRespVO.id(insert.getId()));
    }

    @Override
    public void remove(Long id, Long uid) {
        UserEmoji userEmoji = userEmojiDao.getById(id);
        AssertUtil.isNotEmpty(userEmoji, "表情包不能为空");
        AssertUtil.equal(uid, userEmoji.getUid(), "小黑子，别人表情不是你能删的");
        userEmojiDao.removeById(id);
    }
}
